package com.carleasoft.mps.cms.utils;

import com.carleasoft.mps.cms.business.article.bean.vo.CategoryNameTreeVo;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author taoyujing
 * @date 2021-07-16 14:15
 * @project service
 */
public class TreeUtil {
    private volatile static TreeUtil INSTANCE;
    private final String parentCode = "0";
    // 构造方法私有化
    private TreeUtil() {

    }

    // 获取树工具单例 （DCL单例）
    public static TreeUtil getInstance() {
        if (INSTANCE == null) {
            synchronized (TreeUtil.class) {
                if (INSTANCE == null) {
                    INSTANCE = new TreeUtil();
                }
            }
        }
        return INSTANCE;
    }

    public List<CategoryNameTreeVo> enquireTree(List<CategoryNameTreeVo> CategoryNameTreeVoList) {

        if (CategoryNameTreeVoList.isEmpty()) {
            return null;
        }

        // 过滤空对象
        List<CategoryNameTreeVo> CategoryNameTreeVos = CategoryNameTreeVoList.stream().filter(CategoryNameTreeVo -> CategoryNameTreeVo != null).collect(Collectors.toList());
        List<CategoryNameTreeVo> list = new LinkedList<>();
        for (CategoryNameTreeVo categoryNameTreeVo : CategoryNameTreeVos) {
            if (parentCode.equals(categoryNameTreeVo.getParentCode())) {
                List<CategoryNameTreeVo> childrenNode = getChildrenNode(categoryNameTreeVo.getCategoryCode(), CategoryNameTreeVos, categoryNameTreeVo.getChildren());
                if (childrenNode != null && childrenNode.size() >0) categoryNameTreeVo.setChildren(childrenNode);
                list.add(categoryNameTreeVo);
            }
        }

        return list;

    }

    private List<CategoryNameTreeVo> getChildrenNode(String categoryCode, List<CategoryNameTreeVo> categoryNameTreeVos, List<CategoryNameTreeVo> list2) {
        for (CategoryNameTreeVo department : categoryNameTreeVos) {
            if (categoryCode.equals(department.getParentCode())){
                // 递归获取子节点下的子节点，即设置树控件中的children
                list2.add(department);
                department.setChildren(getChildrenNode(department.getCategoryCode(), categoryNameTreeVos, department.getChildren()));
            }
        }
        return list2;
    }
}
